# Copyright 2024 Bytedance Ltd. and/or its affiliates
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Note that we don't combine the main with ray_trainer as ray_trainer is used by other main.
"""
import os
import ray
import time
import hydra
import wandb
import random
from omegaconf import OmegaConf

from mindspeed_llm.tasks.posttrain.launcher import get_trainer

config_name = None


# 生成带时间戳和随机值的唯一名称
def generate_run_name(base_name):
    timestamp = time.strftime("%m%d-%H%M")  # 当前时间（格式：YYYYMMDD-HHMMSS）
    random_value = random.randint(1000, 9999)  # 生成一个4位随机数
    return f"{base_name}_time_{timestamp}_tag_{random_value}"


@hydra.main(config_path='configs/rlxf', config_name='ppo_trainer_llama32_1b', version_base=None)
def main(config):
    # 从hydra.conf中获取config_name
    from hydra.core.hydra_config import HydraConfig
    global config_name
    config_name = HydraConfig.get().job.config_name

    if not ray.is_initialized():
        # this is for local ray cluster
        ray.init(runtime_env={
            'env_vars': {"RAY_EXPERIMENTAL_NOSET_ASCEND_RT_VISIBLE_DEVICES": "True",
                         'TOKENIZERS_PARALLELISM': 'true',
                         'NCCL_DEBUG': 'WARN'
                         }})

    ray.get(main_task.remote(config))


@ray.remote
def main_task(config):
    config_dict = OmegaConf.to_container(config, resolve=True)
    config_dict["env_vars"] = dict(os.environ)
    run = wandb.init(project="ray-gpt", name=f"{generate_run_name(config_name)}", config=config_dict)
    try:
        trainer = get_trainer(config.training.stage)(config)
        trainer.train()
    finally:
        run.finish()


if __name__ == '__main__':
    main()
